# 周易八卦算法实现

## 基本概念
- 八卦：乾、坤、震、艮、离、坎、兑、巽
- 六十四卦：由八卦两两组合而成
- 爻：阴爻(--) 和阳爻(—)
- 变爻：由阴变阳或由阳变阴的爻

## 算法设计

```python
import random
import datetime
import calendar
from datetime import datetime, timedelta

class ZhouYiDivination:
    def __init__(self):
        # 八卦名称
        self.bagua_names = ["乾", "兑", "离", "震", "巽", "坎", "艮", "坤"]
        
        # 八卦对应的三爻组合（从下到上）
        self.bagua_yao = {
            "乾": [1, 1, 1],  # 三个阳爻
            "兑": [1, 1, 0],  # 下两个阳爻，上一个阴爻
            "离": [1, 0, 1],
            "震": [0, 0, 1],
            "巽": [1, 1, 0],
            "坎": [0, 1, 0],
            "艮": [1, 0, 0],
            "坤": [0, 0, 0]   # 三个阴爻
        }
        
        # 八卦五行属性
        self.bagua_elements = {
            "乾": "金",
            "兑": "金",
            "离": "火",
            "震": "木",
            "巽": "木",
            "坎": "水",
            "艮": "土",
            "坤": "土"
        }
        
        # 六十四卦名称和解释
        self.hexagrams = self._init_hexagrams()
        
    def _init_hexagrams(self):
        # 初始化六十四卦的名称和基本解释
        # 这里只列出部分示例，实际实现需要完整的六十四卦数据
        hexagrams = {
            "111111": {
                "name": "乾为天",
                "description": "大吉大利，刚健自强，充满活力。",
                "career": "事业蒸蒸日上，适合开拓进取。",
                "love": "感情稳定，但需注意过于刚强可能引起矛盾。",
                "health": "精力充沛，但需注意休息，避免过度劳累。",
                "fortune": "财运亨通，适合投资与拓展。"
            },
            "000000": {
                "name": "坤为地",
                "description": "柔顺包容，厚德载物，利于安守本分。",
                "career": "稳步发展，适合脚踏实地工作。",
                "love": "感情温和，包容与理解是关键。",
                "health": "身体状况平稳，注意休养生息。",
                "fortune": "财运稳定，适合储蓄与稳健投资。"
            },
            # 其他卦象数据...
        }
        return hexagrams
    
    def cast_hexagram(self, birth_date, current_time, question_type):
        """
        根据用户生日、当前时间和问题类型生成卦象
        
        参数:
        birth_date: 用户生日，格式为"YYYY-MM-DD"
        current_time: 当前时间，格式为"YYYY-MM-DD HH:MM:SS"
        question_type: 问题类型，如"事业"、"爱情"、"健康"等
        
        返回:
        卦象结果字典
        """
        # 将生日和当前时间转换为数值
        birth_dt = datetime.strptime(birth_date, "%Y-%m-%d")
        current_dt = datetime.strptime(current_time, "%Y-%m-%d %H:%M:%S")
        
        # 计算年龄和生肖
        age = current_dt.year - birth_dt.year
        if (current_dt.month, current_dt.day) < (birth_dt.month, birth_dt.day):
            age -= 1
        
        # 计算生肖
        chinese_zodiac = ["鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"]
        zodiac_index = (birth_dt.year - 4) % 12
        zodiac = chinese_zodiac[zodiac_index]
        
        # 根据生日、当前时间和问题类型生成六爻
        seed = (
            birth_dt.year + birth_dt.month + birth_dt.day +
            current_dt.year + current_dt.month + current_dt.day +
            current_dt.hour + current_dt.minute + current_dt.second +
            len(question_type) + age
        )
        random.seed(seed)
        
        # 生成六爻（0表示阴爻，1表示阳爻）
        yao = []
        changing_yao = []  # 记录变爻位置
        
        for i in range(6):
            # 模拟传统的掷钱币方式：三枚钱币，正面为3，反面为2
            # 三枚钱币的和：6=老阳(9)，7=少阳(7)，8=少阴(8)，9=老阴(6)
            coins = [random.randint(2, 3) for _ in range(3)]
            coin_sum = sum(coins)
            
            if coin_sum == 6:  # 老阳，阳爻有变化
                yao.append(1)
                changing_yao.append(i)
            elif coin_sum == 7:  # 少阳，阳爻无变化
                yao.append(1)
            elif coin_sum == 8:  # 少阴，阴爻无变化
                yao.append(0)
            elif coin_sum == 9:  # 老阴，阴爻有变化
                yao.append(0)
                changing_yao.append(i)
        
        # 生成本卦
        original_hexagram = ''.join(map(str, yao))
        
        # 生成变卦（如果有变爻）
        changed_yao = yao.copy()
        for i in changing_yao:
            changed_yao[i] = 1 - changed_yao[i]  # 0变1，1变0
        changed_hexagram = ''.join(map(str, changed_yao))
        
        # 获取上下卦
        upper_trigram = original_hexagram[3:6]
        lower_trigram = original_hexagram[0:3]
        
        # 查找卦象解释
        hexagram_info = self.hexagrams.get(original_hexagram, {
            "name": "未知卦象",
            "description": "请查阅详细的周易资料。",
            "career": "暂无解析",
            "love": "暂无解析",
            "health": "暂无解析",
            "fortune": "暂无解析"
        })
        
        # 根据问题类型提供针对性解释
        specific_advice = hexagram_info.get(question_type.lower(), "请参考卦象总体解释")
        
        # 计算吉凶指数（示例算法，可根据实际需求调整）
        lucky_elements = ["木", "火"] if question_type == "事业" else ["金", "水"] if question_type == "爱情" else ["土"]
        upper_element = self.bagua_elements.get(self._trigram_to_bagua(upper_trigram), "")
        lower_element = self.bagua_elements.get(self._trigram_to_bagua(lower_trigram), "")
        
        luck_score = 0
        if upper_element in lucky_elements:
            luck_score += 2
        if lower_element in lucky_elements:
            luck_score += 2
        luck_score += len(changing_yao)  # 变爻越多，变化越大
        
        # 归一化到1-5分
        luck_score = max(1, min(5, luck_score))
        
        # 返回结果
        result = {
            "original_hexagram": {
                "code": original_hexagram,
                "name": hexagram_info["name"],
                "description": hexagram_info["description"]
            },
            "changed_hexagram": {
                "code": changed_hexagram,
                "name": self.hexagrams.get(changed_hexagram, {}).get("name", "未知变卦")
            } if changing_yao else None,
            "changing_yao": changing_yao,
            "upper_trigram": self._trigram_to_bagua(upper_trigram),
            "lower_trigram": self._trigram_to_bagua(lower_trigram),
            "question_type": question_type,
            "specific_advice": specific_advice,
            "luck_score": luck_score,
            "user_info": {
                "age": age,
                "zodiac": zodiac
            },
            "divination_time": current_time
        }
        
        return result
    
    def _trigram_to_bagua(self, trigram):
        """将三爻代码转换为八卦名称"""
        for name, yao in self.bagua_yao.items():
            if ''.join(map(str, yao)) == trigram:
                return name
        return "未知卦"

# 使用示例
if __name__ == "__main__":
    divination = ZhouYiDivination()
    result = divination.cast_hexagram(
        birth_date="1990-01-15",
        current_time="2025-05-28 10:30:00",
        question_type="事业"
    )
    print(result)
```
